package com.chuanyang.driverh.mainstart;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseActivity;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.UpdateappData;
import com.chuanyang.driverh.responseresult.UpdateappResult;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.JSAppUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.NetUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.ExitAppEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.widget.CircleProgressBar;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.GenericsCallback;

import java.io.File;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class SplashActivity extends BaseActivity {
    private NetWorkReceiver receiver;
    private Dialog dialog;
    private LinearLayout ll_splash_update;
    private CircleProgressBar cp_splash_update;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            finishIfNecessary();
//            getPermission();
            setContentView(R.layout.start_act_splash);
            setView();
            checkNetwork();

        }catch (Exception e){
            getAppinfo();
            e.printStackTrace();
        }
    }

/*    private void getPermission() {
        try {
            PermissoinUtil.checkAndRequestPermissions(activityContext, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    private void setView(){
        ll_splash_update = (LinearLayout) findViewById(R.id.ll_splash_update);
        cp_splash_update = (CircleProgressBar) findViewById(R.id.cp_splash_update);
        ( (TextView)findViewById(R.id.tv_version)).setText(JSAppUtil.getPackageInfo(activityContext).versionName);
    }

    /**
     * 手机的安装完成界面点击打开 而不是点击完成的时候
     * home掉应用 再次点击图标有时会出现 重启应用的情况
     * 此时创建立即finish掉
     */
    private void  finishIfNecessary(){
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            onBackPressed();
            return;
        }
    }

    /**
     * 检查网络连接状态
     */
    private void checkNetwork() {
        if(NetUtil.getNetWorkType(this)== ConstUtil.NETWORK_TYPE_DISCONNECTED){
            register(); //无网络的情况下 注册网络状态改变的广播
            dialog= DialogUtil.myDialog(this, "无网络连接",  "取消", "设置", "当前无网络，是否设置", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        if(v.getId()== R.id.dialog_btn_left){
                            EventBus.getDefault().post(new ExitAppEvent(true));
                        }else{
                            NetUtil.openSystemSettings(activityContext);
                        }
                        dialog.cancel();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }else{

            try {
                getAppinfo();
//                sleepToNextPage();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void getAppinfo() {
        String url = ConstUtil.UPDATE_URL;
        OkHttpUtils
                .get()//
                .url(url)//
                .addParams("id", ConstUtil.APP_ID)//
                .build()//
                .execute(new GenericsCallback<UpdateappResult>(new JsonGenericsSerializator())
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                            sleepToNextPage();
                    }

                    @Override
                    public void onResponse(UpdateappResult result, int id)
                    {
                        if (result.getCode() == ConstUtil.OK) {
                            //登录成功返回用户信息
                            if (result.getData() != null) {
                                UpdateappData updateappData = result.getData();
                                checkUpdate(updateappData);
                            }
                        } else {
                            PrintUtil.toast(SplashActivity.this, "请求网络失败");
                            try {
                                sleepToNextPage();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void checkUpdate(final UpdateappData updateappData) {
        PackageInfo info = JSAppUtil.getPackageInfo(activityContext);
       int  localVersionCode=info.versionCode;
//        String versionName=info.versionName;
        int serverVersonCode = updateappData.getVersionCode();
        LogUtils.e("localVersionCode", serverVersonCode + "----------" + localVersionCode);//: 0----------2
        if (serverVersonCode > localVersionCode) {//有更新
           dialog= DialogUtil.myDialogIfDismiss(activityContext, "更新", "取消", "更新", updateappData.getDescription(), new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   if(v.getId()== R.id.dialog_btn_left){//用户点击取消更新
                       if (updateappData.isForceUpdate()){//强制更新
                           EventBusUtil.postEvent(new ExitAppEvent(true) );
                           return;
                       }else {
                           sleepToNextPage();
                       }
                   }else{//用户点击更新
                        download(updateappData.getDownloadUrl());
                   }
                   dialog.cancel();
               }
           },false);
        } else {
            //最新版本
            try {
                sleepToNextPage();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 下载
     *
     * @param url
     */
    private void download(String url) {
        ll_splash_update.setVisibility(View.VISIBLE);
        OkHttpUtils//
                .get()//
                .url(url)//
                .build()//
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "chuanyanghengsui.apk")//
                {
                    @Override
                    public void inProgress(float current, long total, int id)
                    {
                        int currentpro = (int) (current * 100);
                        cp_splash_update.setProgress(currentpro);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        sleepToNextPage();
                    }

                    @Override
                    public void onResponse(File file, int id)
                    {
                        showInstallDialog(SplashActivity.this, file.getAbsolutePath());
                        System.out.println(file.getAbsolutePath());
                    }
                });

    }


    /**
     * 弹出安装对话框
     *
     * @param context
     */
    private void showInstallDialog(Context context, final String savePath) {
      /*  System.out.println("安装....");
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");// 动作
        intent.addCategory("android.intent.category.DEFAULT");// 类别
        Uri data = Uri.parse("file://" + savePath);
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        // startActivity(intent); 不能调用onActivityResult在处理完毕之后
        startActivityForResult(intent, 3);*/


        File file = new File(savePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setAction("android.intent.action.VIEW");// 动作
        intent.addCategory("android.intent.category.DEFAULT");// 类别
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, "com.chuanyang.driverh.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }

        startActivityForResult(intent, 0);

    }

    /**
     * 调用onActivityResult在处理完毕之后 在请求页面关闭之后
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        sleepToNextPage();
    }

    private void sleepToNextPage() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                SystemClock.sleep(1000);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                try {
                    gotoActivity();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.execute();

    }




    /**
     * 进行界面的调转
     */
    private void gotoActivity(){
        if (!StringUtil.isBlank(SharedPrefUtil.getPwd())){
            BaseApplication.getInstance().setDriverInfo();
            DriverInfoData driverInfoData= BaseApplication.getInstance().getDriverInfo();
            if (driverInfoData!=null &&driverInfoData.getFleet()!=null && driverInfoData.getFleet().getFleetLeader().equals(driverInfoData.getDriverId())){
                ActivityUtil.startActivity(activityContext, MainActivityLeader.class);
            }else{
                ActivityUtil.startActivity(activityContext, MainActivityDriver.class);
            }

        }else{
            ActivityUtil.startActivity(activityContext, LoginActivity.class,true);
        }
}


    /**
     * 监听网络状态改变的广播接收器
     * 一开始有网络状态的情况下 也会接收一次广播  所以在无网络的情况下才进行注册
     * @author joyskim
     */
    class NetWorkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (NetUtil.getNetWorkType(activityContext)) {
                case ConstUtil.NETWORK_TYPE_DISCONNECTED:
                    break;
                case ConstUtil.NETWORK_TYPE_MOBILE :
                case ConstUtil.NETWORK_TYPE_WIFI :
                    try {
                        unregisterReceiver();
                        getAppinfo();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver();
        super.onDestroy();
    }

    /**
     * 注册监听网络状态广播
     */
    private void register() {
        receiver=new NetWorkReceiver();
        IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }



    private void unregisterReceiver(){
        if(receiver!=null) {
            unregisterReceiver(receiver); //无网络的情况下 注册了广播 需要取消注册
            receiver=null;
        }
    }



    @Override
    public void onBackPressed() {
        EventBus.getDefault().post(new ExitAppEvent(true));
    }

}